package com.zp.demopractice1;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.List;

/**
 * Created by izp on 2017/3/25.
 */

public class CarouselView extends FrameLayout {
    private static final int S_MSG_LOOP = 1000;//这就是一个消息，我觉得以后消息类型的都配置到id里面去，当做资源引用？

    private static long S_LOOP_INTERVAL = 5000;//间隔时间
    private LinearLayout mLinearPosition = null;
    private ViewPager mViewPager = null;
    private TimingHandler mTimingHandler = null;

    //真实显示的banner view 集合
    private List<View> mViewList;
    //真实显示的banner view个数
    private int mViewSize;

    public CarouselView(@NonNull Context context) {
        super(context);
        init();
    }

    public CarouselView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        initViewPager();
        initLinearPosition();
        this.addView(mViewPager);
        this.addView(mLinearPosition);
    }

    private void initLinearPosition() {
        mLinearPosition = new LinearLayout(getContext());

        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;//位运算
        layoutParams.bottomMargin = getResources().getDimensionPixelSize(R.dimen.dimen_9dp);

        mLinearPosition.setOrientation(LinearLayout.HORIZONTAL);
        mLinearPosition.setPadding(getResources().getDimensionPixelSize(R.dimen.dimen_9dp),0,0,0);
        mLinearPosition.setLayoutParams(layoutParams);

    }

    private void initViewPager() {
        mViewPager = new ViewPager(getContext());//获取View的Context,没有耗时任务可以直接使用context引用
//        都是在FrameLayout中动态创建View然后添加到FrameLayout中
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//       这个LayoutParams的使用确实有点捉摸不透,暂时定为外层是什么ViewGroup就用谁的LayoutParams
        mViewPager.setLayoutParams(layoutParams);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                KLog.i("position :"+position+"    positionOffset :"+positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                updateLinearPosition();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void updateLinearPosition() {
        if (null!=mViewList && mViewList.size()>=0){
            if (mLinearPosition!=null && mLinearPosition.getChildCount() != mViewSize) {//如果指示圆点的数量不等于pager的数量
                int diffCnt = mLinearPosition.getChildCount() - mViewSize;//获取差数
                boolean needAdd = diffCnt < 0;//如果差速为负,则,还需要继续添加.
                diffCnt = Math.abs(diffCnt);//获取绝对值?
                for (int i = 0; i < diffCnt; i++) {
                    if (needAdd) {
                        ImageView img = new ImageView(getContext());
                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        layoutParams.rightMargin = getResources().getDimensionPixelOffset(R.dimen.dimen_9dp);
                        img.setLayoutParams(layoutParams);
                        img.setBackgroundResource(R.mipmap.banner_point);
                        mLinearPosition.addView(img);
                    } else {
                        mLinearPosition.removeViewAt(0);//也就是如果差数是正的,那么就用子View的第一个开始移除image
                    }
                }
                int curPos = mViewPager.getCurrentItem();
                for (int i = 0; i < mLinearPosition.getChildCount(); i++) {
                    if (i == (curPos % mViewSize)) {//余数,如果当前item的值小于size,那么余数就是本身.
                        mLinearPosition.getChildAt(i).setBackgroundResource(R.mipmap.banner_point_select);
                    } else {
                        mLinearPosition.getChildAt(i).setBackgroundResource(R.mipmap.banner_point);
                    }
                }
            }
        }
    }
    public void setAdapter(PagerAdapter adapter) {
        mViewPager.setAdapter(adapter);
        updateLinearPosition();
    }
    public void setViewList(List<View> viewList) {
        this.mViewList = viewList;
        if (viewList != null && viewList.size() != 0) {
            mViewSize = viewList.size();
            CarouselAdapter carouselAdapter = new CarouselAdapter(viewList);
            setAdapter(carouselAdapter);
        }
    }

    public void isShowAnim(boolean isShow){
        if (isShow){
            /**
             *假设现在ViewPager在A页现在滑出B页，则:
             A页的position变化就是( 0, -1]
             B页的position变化就是[ 1 , 0 ]
             */
            mViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
                @Override
                public void transformPage(View page, float position) {
                    int pageWidth = page.getWidth();
                    if (position<-1){//已经离开屏幕
                        page.setRotation(0f);
                    }else if (position<=1){ // a页滑动至b页 ； a页从 0.0 ~ -1 ；b页从1 ~ 0.0
                        if (position<0){//还在A页？
                            float mRot = 20f*position;//20倍滑动偏移是什么意思
                            page.setPivotX(page.getMeasuredWidth()*0.5f);//用来设置缩放的锚点,x点在宽的一半中心
                            page.setPivotY(page.getMeasuredHeight());//但是锚点的Y轴又是底部，也就是说锚点在底部的中心？
                            page.setRotation(mRot);
                        }else {
                            float mRot = (20f * position);
                            page.setPivotX(page.getMeasuredWidth() * 0.5f);
                            page.setPivotY(page.getMeasuredHeight());
                            page.setRotation(mRot);
                        }
                    }else {
                        page.setRotation(0);
                    }
                }
            });
        }
    }
    public static void setLoopInterval(long loopInterval) {
        S_LOOP_INTERVAL = loopInterval;
    }

    public void startLoop(boolean flag){
        if (flag){
            if (null==mTimingHandler){
                mTimingHandler = new TimingHandler(this);
            }else {
                mTimingHandler.sendEmptyMessageDelayed(S_MSG_LOOP,S_LOOP_INTERVAL);//每隔几秒发送一个int型的消息
            }
        }else {
            if (mTimingHandler != null) {
                if (mTimingHandler.hasMessages(S_MSG_LOOP)) {
                    mTimingHandler.removeMessages(S_MSG_LOOP);
                }
            }
        }
    }

    private static class TimingHandler extends Handler{
        private WeakReference<CarouselView> wsView = null;

        public TimingHandler(CarouselView view) {
            super(Looper.getMainLooper());//疑问
            this.wsView = new WeakReference<CarouselView>(view);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//            if (this.wsView==null){//疑问，wsView.get()为空的区别
//                return;
//            }
            if (null!=wsView){
                CarouselView carouselView = wsView.get();
                if ( carouselView!= null && carouselView.mViewPager != null &&
                        carouselView.mViewPager.getAdapter() != null &&
                        carouselView.mViewPager.getAdapter().getCount() > 0) {

                    int curPos = carouselView.mViewPager.getCurrentItem();//获取当前viewPagerItem
                    KLog.i("获取当前ViewPager的item:"+curPos);
                    curPos = (curPos + 1) % carouselView.mViewPager.getAdapter().getCount();//疑问？当前item+1除以pager总数取整是什么鬼
                    KLog.i("获取当前ViewPager的item加1除以item总数取整:"+curPos+"总数"+carouselView.mViewPager.getAdapter().getCount());
                    carouselView.mViewPager.setCurrentItem(curPos);
                    sendEmptyMessageDelayed(S_MSG_LOOP, S_LOOP_INTERVAL);
                }else {
                    sendEmptyMessageDelayed(S_MSG_LOOP, S_LOOP_INTERVAL);
                }

            }

        }
    }

    public static class CarouselAdapter extends PagerAdapter{
        private List<View> viewList;

        public CarouselAdapter(List<View> viewList) {
            this.viewList = viewList;
        }

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;//int的最大值是什么意思？
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(viewList.get(position%viewList.size()));
            return viewList.get(position%viewList.size());
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position%viewList.size()));//只要position比size小，那么get的就是当前position=size
        }

    }

}
